package com.example.forumadminbackend.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET_KEY_STRING = "forum_admin_secret_key_long_enough_for_hs256";
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET_KEY_STRING); // 直接使用Algorithm来处理密钥
    private static final long EXPIRATION = 1000 * 60 * 60 * 12; // 12小时

    public static String generateToken(String adminId, String username) {
        try {
            return JWT.create()
                    .withClaim("adminId", adminId)
                    .withClaim("username", username)
                    .withIssuedAt(new Date())
                    .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION))
                    .sign(ALGORITHM);
        } catch (JWTCreationException exception){
            // Invalid Signing configuration / Couldn't convert Claims.
            // 实际应用中应该记录日志或抛出自定义异常
            throw new RuntimeException("Error generating JWT token", exception);
        }
    }

    public static DecodedJWT parseToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .build();
            return verifier.verify(token);
        } catch (JWTVerificationException exception){
            // Invalid signature/claims
            // 实际应用中应该记录日志或抛出自定义异常
            throw new RuntimeException("Error verifying JWT token", exception);
        }
    }
} 